package com.sua.mybatis;

import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.sua.mybatis.po.UserPO;

public class MybatiseFirst {
	
	
	@Test
	public void findUserByIdTest() throws IOException {
		String resource = "config/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
 		SqlSessionFactory sqlSessionFactory =(SqlSessionFactory) new SqlSessionFactoryBuilder().build(inputStream);
 		SqlSession sqlSession = sqlSessionFactory.openSession();
 		
 		//selectOne
 		//UserPO user = sqlSession.selectOne("test.findUserById",1);
 		
     	//模糊查询
 		//why这里不能根据"%${name}%"而必须使用"%"#{name}"%"只能是简单类型 String不是简单类型 所以只能是value
 		/*	List<UserPO> Users = sqlSession.selectList("test.findUserByName","a");
 		for(UserPO users:Users) {
 			System.out.println(users.toString());
 		}
 		*/
 		sqlSession.close();
 		
	}
	
	@Test
	public void insertUser() throws IOException {
		String resource = "config/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
 		SqlSessionFactory sqlSessionFactory =(SqlSessionFactory) new SqlSessionFactoryBuilder().build(inputStream);
 		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserPO user = new UserPO();
		user.setName("suaxu1");
 		user.setPassword("123455");
 		user.setBirthday(new Date());
 		sqlSession.insert("test.insertUser",user);
 		System.out.println(user.getId());

 		sqlSession.commit();
 		System.out.println(user.getId());
 		sqlSession.close();
 		
	}
	
	@Test
	public void deleteUser() throws IOException {
		String resource = "config/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
 		SqlSessionFactory sqlSessionFactory =(SqlSessionFactory) new SqlSessionFactoryBuilder().build(inputStream);
 		SqlSession sqlSession = sqlSessionFactory.openSession();
 		sqlSession.delete("test.deleteUser",3); 
 		sqlSession.commit();
 		sqlSession.close();
	}
	
	
	
	@Test
	public void updateUser() throws IOException{
		String resource = "config/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserPO user = new UserPO();
		user.setName("xx");
		user.setPassword("bbb");
		user.setId(5);
		sqlSession.update("test.updateUser",user);
		sqlSession.commit();
		sqlSession.close();
	}
	

}


